'use strict';
/** 邮件系统 */
module.exports.run = function(d,s){
    const bs = require("../module/base");
    switch(d[1]){
        case 1:{ //获取邮件列表
            bs.DB.query(`SELECT A.mid,title,body,ext FROM mails A 
            LEFT JOIN sysmailrecord B ON A.touserid = 0 AND A.mid = B.mid AND B.userid = $1
            WHERE (A.touserid = $1 OR (A.touserid = 0 AND B.userid IS NULL)) AND A.gettime IS NULL AND A.gametp = $2`, (rs)=>{
                d[2] = rs.rows;
                bs.send(s, d);
            },[s.U.uid,s.U.gametp]);
            break;
        }case 2:{ //发送邮件
            break;
        }case 3:{ //领取邮件附件
            if(!bs.checkParam(["mid"], d)) return;
            bs.DB.query("SELECT touserid,ext,gettime FROM mails WHERE (touserid = $1 OR touserid = 0) AND gametp = $2 AND mid = $3", (rs)=>{
                if(rs.rows.length == 0 || rs.rows[0].gettime != null){
                    return bs.sendE(s, 8);
                }
                let upsql = "";
                if(rs.rows[0].touserid == 0) upsql = "INSERT INTO sysmailrecord VALUES($1,$2) ON CONFLICT (mid,userid) DO NOTHING";
                else upsql = "UPDATE mails SET gettime = NOW() WHERE mid = $1 AND touserid = $2 AND gettime IS NULL";
                bs.DB.query(upsql, (rs2)=>{
                    if(rs2.rowCount > 0){
                        if(rs.rows[0].ext && rs.rows[0].ext.length > 0){
                            const bag = require("./bag");
                            bag.add(rs.rows[0].ext, s, null, 5, d[2].mid);
                        }
                    }
                },[d[2].mid,s.U.uid])
            },[s.U.uid,s.U.gametp,d[2].mid])
            break;
        }
    }
}

/** 发送邮件 */
module.exports.send = function(gametp,userid, touserid, title, context, ext){
    const bs = require("../module/base");
    bs.DB.query("INSERT INTO mails(gametp,sendid,touserid,title,body,ext) VALUES($1,$2,$3,$4,$5,$6)",(rs)=>{
        
    },[gametp, userid, touserid, title, context, ext])
}